﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using DevelopmentKit.Domain;
using DevelopmentKit.Extensions.MvcContrib;
using DevelopmentKit.Extensions.SharpArch.DataContext;
using SharpArch.NHibernate.Web.Mvc;

namespace DevelopmentKit.Web.Controllers
{
    public class RoleController : BaseController
    {

        private readonly IDataContext _query;

        public RoleController(IDataContext query)
        {
            _query = query;
        }


        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="page"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Index(string keyword, int page = 1, int size = 12)
        {
            var query = _query.FindAll<Role>().Where(m => m.Enterprise == Current.Enterprise);
             
            if (!string.IsNullOrEmpty(keyword))
            {
                query = query.Where(m => m.Name.Contains(keyword));
            }

         
            var model = query.OrderByDescending(m => m.Modified).AsPagination(page, size);
             
            return View(model);
        }
        /// <summary>
        /// 获取权限列表
        /// </summary>
        /// <returns></returns>
        private List<SelectListItem> GetRights()
        {
            return _query.FindAll<Right>().Where(m => m.Enterprise == Current.Enterprise).Select(
                    m => new SelectListItem { Text = m.Name, Value = m.Id.ToString(CultureInfo.InvariantCulture) }).ToList();
        }


      

        /// <summary>
        /// 创建角色
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Create()
        { 
            ViewBag.Rights = GetRights();
            return View(new RoleViewModel());
        } 

        /// <summary>
        /// 提交 新增角色
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Transaction]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(RoleViewModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var entity = new Role
                                     {

                                         Created = DateTime.Now,
                                         Modified = DateTime.Now,
                                         Rights = new List<Right>(),
                                         Name = model.Name,
                                         Remark = model.Remark,
                                         Enterprise = Current.Enterprise
                                     };
                    if(null!=model.Rights&&model.Rights.Any())
                    {
                        foreach (var id in model.Rights)
                        {
                            var role = _query.Get<Right>(id);
                            entity.Rights.Add(role);
                        }
                    }
                    _query.Save(entity);
                    return RedirectToAction("Index", "Role");
                }
            }
            catch
            {
                ModelState.AddModelError("", "系统繁忙,请稍后再试");
            }
            ViewBag.Rights = GetRights();
            return View(model);
        }

       /// <summary>
       /// 修改角色
       /// </summary>
       /// <param name="id"></param>
       /// <returns></returns>
       [HttpGet]
        public ActionResult Edit(int id)
        {
            var entity = _query.Get<Role>(id);
            if (null == entity)
            {
                return View("NoFound");
            }
            var model = new RoleViewModel
               {
                   Name = entity.Name,
                   Remark = entity.Remark,
                   Rights = entity.Rights.Select(x => x.Id).ToArray()
               };
           ViewBag.Rights = GetRights();
           return View(model); 
        }

        /// <summary>
        /// 修改角色 提交
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        [HttpPost]
       [Transaction]
       [ValidateAntiForgeryToken]
        public ActionResult Edit(int id, RoleViewModel model, string returnUrl)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var entity = _query.Get<Role>(id);
                    if (null == entity)
                    {
                        return View("NoFound");
                    }
                    entity.Name = model.Name;
                    entity.Remark = model.Remark;
                    entity.Modified = DateTime.Now;

                    if (null != model.Rights && entity.Rights.Any(x => !model.Rights.Contains(x.Id)))
                    {
                        var list = entity.Rights.Where(x => !model.Rights.Contains(x.Id)).ToArray();
                        foreach (var right in list)
                        {
                            entity.Rights.Remove(right);
                        }
                    }
                    if (null != model.Rights && model.Rights.Any())
                    {
                        foreach (var rightId in model.Rights)
                        {
                            var action = _query.Get<Right>(rightId);
                            if (entity.Rights.Count == 0 || entity.Rights.Any(x => x != action))
                            {
                                entity.Rights.Add(action);
                            }
                        }
                    }
                    _query.Save(entity); 
                    if (string.IsNullOrEmpty(returnUrl))
                    {
                        return RedirectToAction("Index");
                    }
                    return Redirect(returnUrl);

                }
            }
            catch
            {
                ModelState.AddModelError("", "系统繁忙,请稍后再试");
            }
            ViewBag.Rights = GetRights();
            return View();
        }

     
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <param name="returnUrl"></param>
        /// <returns></returns> 
        [HttpPost]
        [Transaction]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(int id, string returnUrl)
        {
            var entity = _query.Get<Role>(id);

            if (null == entity)
            {
                return View("NoFound");
            }  
            _query.Delete(entity);
            if (string.IsNullOrEmpty(returnUrl))
            {
                return RedirectToAction("Index");
            }
            return Redirect(returnUrl);
        }
      
    }
}
